package com.liyongjian.xhban.interceptor;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


/**
 * 拦截未登录的用户信息
 * 
 */
public class LoggerInterceptor implements HandlerInterceptor {

  private Logger logger = LoggerFactory.getLogger(LoggerInterceptor.class);

  private Long startExecuteTime = 0L;


  private String getIpAddr(HttpServletRequest request) {
    String ip = request.getHeader("x-forwarded-for");
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getRemoteAddr();
    }
    return ip;
  }

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {

    startExecuteTime = System.currentTimeMillis();
    Enumeration<String> enu = request.getParameterNames();
    StringBuilder sb = new StringBuilder();

    sb.append("Start ==>> Request IP:[").append(getIpAddr(request)).append("], Request URL:[")
        .append(request.getRequestURI()).append("], Request Parameter:[");
    while (enu.hasMoreElements()) {
      String paraName = (String) enu.nextElement();
      sb.append("&").append(paraName).append("=").append(request.getParameter(paraName))
          .append(" ");
    }
    sb.append("]");
    logger.debug(sb.toString());
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
      ModelAndView modelAndView) throws Exception {
    Long executeTime = System.currentTimeMillis() - startExecuteTime;
    logger.debug(new StringBuilder("End ==>> ").append(request.getRequestURI())
        .append(", execute time: ").append(executeTime).append("ms").toString());
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
      Object handler, Exception ex) throws Exception {

  }

}
